﻿using llm_net.Infrastructure.Helpers;
using llm_net.Models;
using llm_net.Services.Abstractions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace llm_net.Services.Implementations
{
    public class VectorDbService: IVectorDbService
    {
        private List<Product> _products = new();
        private readonly ITongyiApiService _tongyiApiService;
        private readonly ILogger<VectorDbService> _logger;
        private readonly string _dataFilePath;
        private readonly object _lockObject = new();

        public VectorDbService(ITongyiApiService tongyiApiService, IConfiguration configuration, ILogger<VectorDbService> logger)
        {
            _tongyiApiService = tongyiApiService;
            _logger = logger;
            _dataFilePath = Path.Combine(configuration["DataDirectory"] ?? AppContext.BaseDirectory, "products.json");

            Directory.CreateDirectory(Path.GetDirectoryName(_dataFilePath));
        }

        public async Task InitializeAsync()
        {
            lock (_lockObject)
            {
                if (_products.Any())
                {
                    return;
                }
            }

            try
            {
                if (File.Exists(_dataFilePath))
                {
                    _logger.LogInformation($"从文件加载商品数据: {_dataFilePath}");
                    var json = await File.ReadAllTextAsync(_dataFilePath);
                    _products = JsonSerializer.Deserialize<List<Product>>(json) ?? new();
                    _logger.LogInformation($"成功加载 {_products.Count} 个商品");
                    return;
                }

                _logger.LogInformation("初始化示例商品数据...");
                _products = await CreateSampleProductsAsync();

                await SaveProductsToFileAsync();

                _logger.LogInformation($"初始化完成，保存了 {_products.Count} 个商品");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化向量数据库失败");
                throw;
            }
        }

        public async Task<List<Product>> SearchSimilarProductsAsync(float[] queryVector, int topK)
        {
            if (!_products.Any())
            {
                await InitializeAsync();
            }

            var similarityScores = _products
               .Select(p => new { Product = p, Score = VectorMathHelper.CosineSimilarity(queryVector, p.Vector) })
               .OrderByDescending(p => p.Score)
               .Take(topK)
               .ToList();

            return similarityScores.Select(p => p.Product).ToList();
        }

        private async Task<List<Product>> CreateSampleProductsAsync()
        {
            var products = new List<Product>
            {
                new Product
                {
                    Id = "P001",
                    Name = "幻影电竞鼠标",
                    Description = "高精度传感器，适合电竞游戏，RGB灯光",
                    Tags = new List<string> { "游戏鼠标", "RGB灯光", "有线连接" }
                },
                new Product
                {
                    Id = "P002",
                    Name = "极光无线鼠标",
                    Description = "无线连接，长续航，适合办公和游戏",
                    Tags = new List<string> { "无线鼠标", "长续航", "办公" }
                },
                new Product
                {
                    Id = "P003",
                    Name = "机械师键盘",
                    Description = "青轴机械键盘，打字节奏感强，全键无冲",
                    Tags = new List<string> { "机械键盘", "青轴", "RGB灯光" }
                },
                new Product
                {
                    Id = "P004",
                    Name = "静音办公键盘",
                    Description = "静音红轴，适合办公室使用，超薄设计",
                    Tags = new List<string> { "办公键盘", "静音", "红轴" }
                },
                new Product
                {
                    Id = "P005",
                    Name = "游戏耳机",
                    Description = "7.1声道，环绕立体声，降噪麦克风",
                    Tags = new List<string> { "游戏耳机", "立体声", "头戴式" }
                }
            };

            foreach (var product in products)
            {
                _logger.LogInformation($"生成商品向量: {product.Name}");
                var text = $"{product.Name} - {product.Description} - {string.Join(", ", product.Tags)}";
                product.Vector = await _tongyiApiService.GetTextEmbeddingAsync(text);
            }

            return products;
        }

        private async Task SaveProductsToFileAsync()
        {
            try
            {
                _logger.LogInformation($"保存商品数据到文件: {_dataFilePath}");
                var jsonData = JsonSerializer.Serialize(_products, new JsonSerializerOptions { WriteIndented = true });
                await File.WriteAllTextAsync(_dataFilePath, jsonData);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存商品数据失败");
            }
        }
    }
}
